import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'
import {
	getSwiperImg,
	getGoodInfo
} from '../api/detail.api.js'

export const useDetailStore = defineStore(
	'detail',
	() => {
		const swiperImgData = ref([]) // 轮播图图片
		const goodInfo = ref({})
		const formatContent = ref('')

		// 获取轮播图图片数据
		const getSwiperImgData = async (id) => {
			let result = await getSwiperImg(id)
			swiperImgData.value = result.message
		}

		// 获取商品信息
		const getGoodInfoData = async (id) => {
			let result = await getGoodInfo(id)
			goodInfo.value = result.message
			formatRichText(goodInfo.value.content || '')
		}

		const formatRichText = (html) => {
			if (!html) return '';
			// 处理图片宽度
			let newContent = html.replace(/<img/gi, '<img style="width:100%;height:auto;display:block;"');
			// 移除图片的width和height属性
			newContent = newContent.replace(/(width|height)=["'][^"']*["']/gi, '');
			formatContent.value = newContent;
		};

		// 跳转详情
		const goDetail = (goods_id) => {
			uni.navigateTo({
				url: `/pages/detail/detail?goods_id=${goods_id}`
			})
		}

		return {
			swiperImgData,
			getSwiperImgData,
			getGoodInfoData,
			goodInfo,
			goDetail,
			formatContent
		}
	}, {
		persist: {
			storage: {
				getItem(key) {
					return JSON.parse(uni.getStorageSync(key)); // 手动替代 destr
				},
				setItem(key, value) {
					uni.setStorageSync(key, JSON.stringify(value));
				},
			},
		}
	}
)